package com.qzboot.basic.service.impl;

import cn.hutool.core.util.StrUtil;
import com.qzboot.common.constant.SysConst;
import com.qzboot.facade.entity.SysMenu;
import com.qzboot.facade.entity.SysUser;
import com.qzboot.facade.entity.SysUserToken;
import com.qzboot.facade.service.SysAuthenticationService;
import com.qzboot.facade.service.SysMenuService;
import com.qzboot.facade.service.SysUserService;
import com.qzboot.facade.service.SysUserTokenService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * @author zengzhihong
 */
@Service
public class SysAuthenticationServiceImpl implements SysAuthenticationService {

    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserTokenService sysUserTokenService;

    @Override
    public Set<String> listUserPerms(Long userId) {
        List<String> permsList;

        //系统管理员，拥有最高权限
        if (userId.equals(SysConst.ADMIN_USER_ID)) {
            List<SysMenu> menuList = sysMenuService.list();
            permsList = new ArrayList<>(menuList.size());
            for (SysMenu menu : menuList) {
                permsList.add(menu.getPerms());
            }
        } else {
            permsList = sysMenuService.listPermsByUserId(userId);
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for (String perms : permsList) {
            if (StrUtil.isBlank(perms)) {
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(StrUtil.COMMA)));
        }
        return permsSet;
    }

    @Override
    public SysUserToken getUserTokenByToken(String token) {
        return sysUserTokenService.getByToken(token);
    }

    @Override
    public SysUser getUserById(Long userId) {
        return sysUserService.getById(userId);
    }
}
